package com.zx.servicelearn.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

/**
 * messenger使用
 */
public class IPCService1_Messenger extends Service {
    Handler mHandler = new Handler() {


        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //接受到客户端消息
                    Log.e("IPCService1", "服务端受到客户端消息：msg——————" + msg.getData().getString("msg"));


                    // TODO: 2018/1/17 回复消息 给客户端
                    Message message = new Message();
                    Bundle mBundle = new Bundle();
                    mBundle.putString("reply", "服务端消息内容");
                    message.setData(mBundle);
                    message.what = 1;
                    Messenger clientMessenger = msg.replyTo;
                    try {
                        clientMessenger.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }


                    break;
                default:
                    break;
            }
        }
    };

    Messenger messenger;

    public IPCService1_Messenger() {
        messenger = new Messenger(mHandler);


    }

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}
